from flask_classy import FlaskView, route
from ..models.account_his import AccountHistory
from ..schema.object import account_histories_resp
from flask import jsonify, g, request
from . import require_login
from ..schema.param import account_history_filter_param
from datetime import datetime, timedelta
from dateutil.relativedelta import *


class AccountHistoriesView(FlaskView):
    support_filter_period = ['last-week', 'last-month', 'last-3-month', 'last-6-month', 'all']

    support_filter_status = ['trading_success', 'pending', 'done', 'all']

    route_base = 'account_histories'

    @require_login
    @route('/filter', methods=['POST'])
    def filter(self):
        data, _ = account_history_filter_param.load(request.get_json())
        current_page = data.get('current_page', 1)
        page_size = data.get('page_size', 10)
        period = data.get('period', 'all')
        status = data.get('status', 'all')

        member = g.member
        select = AccountHistory.select().where(AccountHistory.account == member.account)
        if period and (period not in AccountHistoriesView.support_filter_period):
            pass
        elif not period == 'all':
            now = datetime.now()
            start_date = now
            if period == 'last-week':
                start_date = now + relativedelta(weeks=-1)
            elif period == 'last-month':
                start_date = now + relativedelta(months=-1)
            elif period == 'last-3-month':
                start_date = now + relativedelta(months=-3)
            elif period == 'last-6-month':
                start_date = now + relativedelta(months=-6)

            select = select.where((AccountHistory.created_at >= start_date) & (AccountHistory.created_at <= now))

        if status and (status not in AccountHistoriesView.support_filter_status):
            pass
        elif not status == 'all':
            select = select.where(AccountHistory.status == status)

        return jsonify(
            {
                'items': account_histories_resp.dump(select).data
            }
        )
